import React, {useEffect, useRef, useState} from 'react';
import {
  DeviceEventEmitter,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import Images from '../../images/Images';
import AppEvent from '../../utils/AppEvent';
import {getffly} from '../../utils/common';
import Constants from '../../utils/Constants';
import screen from '../../utils/screen';
import Header from '../../widgets/Header';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import Grabbing from './Grabbing';
import OrderConfirm from './OrderConfirm';

export default ({navigation}) => {
  const data = navigation.state.params.data;

  const [order, setOrder] = useState(null);

  const grabDialog = useRef();
  const confirmDialog = useRef();

  useEffect(() => {
    // console.log('task',data.task[0])
    // console.log('task_type',data.task_type[0])
    // console.log('type_data = ',data.type_data )
  }, []);

  useEffect(() => {
    if (order) {
      // console.log('order',order)
      confirmDialog.current.show(order);
    }
  }, [order]);

//   componentDidMount = () => {
//     this.emitter = DeviceEventEmitter.addListener('grab_end', (data) => {
//       navigation.pop();
//       console.log(this.choosedata);
//       navigation.push('OrderConfirm', {detail: this.choosedata});
//     });
//   };
//   componentWillUnmount = () => {
//     this.emitter && this.emitter.remove();
// }
  const showGrabbing = () => {
    let detail = null;
    let details = [];
    let icons = [];
    for (let item of data.task) {
      if (item.canfetch) {
        details.push(item);
      } else {
        icons.push(item.icon);
      }
    }
    if (details.length > 0) {
      details.sort(function (a, b) {
        var num1 = a.deposit;
        var num2 = b.deposit;

        if (num1) {
          num1 = Number(num1);
        } else {
          num1 = 0;
        }
        if (num2) {
          num2 = Number(num2);
        } else {
          num2 = 0;
        }
        return num2 - num1;
      });
      if (details.length <= 3) {
        var random1 = Math.floor(Math.random() * details.length);
        if (random1 >= details.length) {
          random1 = 0;
        }
        detail = details[random1];
        for (var i = 0; i < details.length; i++) {
          if (i == random1) {
            icons.unshift(details[i].icon);
          } else {
            icons.push(details[i].icon);
          }
        }
        console.log('OrderGrabbingA1', details.length);
        console.log('OrderGrabbingA2', random1);
      } else if (details.length > 3 && details.length <= 6) {
        var dqrandom = 0;
        var random1 = Math.floor(Math.random() * 10);
        var randomA1 = Math.floor(Math.random() * 3);
        var random3 = Math.floor(Math.random() * details.length);
        if (random1 < 5) {
          dqrandom = randomA1;
        } else {
          dqrandom = random3;
        }

        if (dqrandom >= details.length) {
          dqrandom = 0;
        }
        detail = details[dqrandom];
        for (var i = 0; i < details.length; i++) {
          if (i == dqrandom) {
            icons.unshift(details[i].icon);
          } else {
            icons.push(details[i].icon);
          }
        }
        console.log('OrderGrabbingB1', details.length);
        console.log('OrderGrabbingB2', dqrandom);
      } else if (details.length > 6) {
        var dqrandom = 0;
        var random1 = Math.floor(Math.random() * 10);
        var randomA1 = Math.floor(Math.random() * 3);
        var random2 = Math.floor(Math.random() * 10);
        var randomA2 = Math.floor(Math.random() * 6);
        var random3 = Math.floor(Math.random() * details.length);
        if (random1 < 5) {
          dqrandom = randomA1;
        } else {
          if (random2 < 3) {
            dqrandom = randomA2;
          } else {
            dqrandom = random3;
          }
        }

        if (dqrandom >= details.length) {
          dqrandom = 0;
        }
        detail = details[dqrandom];
        for (var i = 0; i < details.length; i++) {
          if (i == dqrandom) {
            icons.unshift(details[i].icon);
          } else {
            icons.push(details[i].icon);
          }
        }
        console.log('OrderGrabbingC1', details.length);
        console.log('OrderGrabbingC2', dqrandom);
      }
    }
    if (detail) {
      grabDialog.current.showDialog(icons, () => {
        setOrder(detail);
      });
    } else {
      var detailA = null;
      var iconsA = [];
      var indexA = 0;
      for (var i = 0; i < data.task.length; i++) {
        if (Number(data.user_level) >= Number(data.task[i].level)) {
          if (
            data.task[i].deposit &&
            Number(data.task[i].deposit) < Number(data.balance)
          ) {
            detailA = data.task[i];
            indexA = i;
            iconsA.push(data.task[i].icon);
            break;
          } else {
            detailA = data.task[i];
            indexA = i;
            iconsA.push(data.task[i].icon);
            break;
          }
        }
      }
      for (var i = 0; i < data.task.length; i++) {
        if (i != indexA) {
          iconsA.push(data.task[i].icon);
        }
      }
      if (detailA) {
        // this.choosedata = detailA;
        grabDialog.current.showDialog(iconsA, () => {
            setOrder(detailA);
          });
      } else {
        var callback = function (index) {};

        var content = Constants.order.no_products_available
        AppModal.showError(content)
      }
    }
  };

  const getConvertData = () => {
    const {amountRange, minLevel} = data.type_data;
    let str1 = Constants.order.current_membership_lv + data.user_level_text;
    let isLevelOk, isLimitOk, isBalanceOk, isContinue;
    if (Number(data.user_level) >= Number(minLevel)) {
      isLevelOk = true;
    } else {
      str1 =
        Constants.order.need_to_upgrade_to_lv +
        minLevel +
        Constants.order.to_grab_this_category;
    }

    let str2 =
      Constants.order.todays_order_limit +
      data.fetched_today +
      '/' +
      data.daily_limit;
    if (data.fetched_today < data.daily_limit) {
      isLimitOk = true;
    } else {
      str2 = Constants.order.upgrade_membership_to_increase_daily_limit;
    }

    let str3 =
      Constants.order.available_balance +
      Constants.appsymbol +
      '  ' +
      data.balance;
    if (Number(data.balance) >= Number(amountRange.min)) {
      isBalanceOk = true;
    } else {
      str3 = Constants.order.minimum_requirement_is + amountRange.min + '.';
    }

    if (isBalanceOk && isLimitOk && isLevelOk) {
      isContinue = true;
    }

    return {
      str1,
      str2,
      str3,
      isLevelOk,
      isLimitOk,
      isBalanceOk,
      isContinue,
    };
  };

  const renderTop = () => {
    const {amountRange, commissionRate, name, icon, minLevel} = data.type_data;
    return (
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'flex-end',
          alignItems: 'center',
          marginTop: screen.PIXEL_30,
        }}>
        <View style={{flex: 1, alignItems: 'center'}}>
          <Image
            source={{uri: icon}}
            style={styles.orderImage}
            resizeMode={'contain'}
          />
        </View>

        <View>
          <View style={styles.tagBg}>
            <Text style={{color: '#000', fontSize: 13}} numberOfLines={1}>
              {'Lv.' + minLevel + Constants.order.and_higher}
            </Text>
          </View>
          <View style={{height: 5}} />
          <View style={styles.tagBg}>
            <Text style={{color: '#000', fontSize: 13}} numberOfLines={1}>
              {Constants.appsymbol +
                ' ' +
                amountRange.min +
                ' ' + Constants.order.to + ' ' +
                amountRange.max}
            </Text>
          </View>
          <View style={{height: 5}} />
          <View style={styles.tagBg}>
            <Text style={{color: '#000', fontSize: 13}} numberOfLines={1}>
              {(commissionRate * 100).toFixed(2) +
                Constants.order.per_order_amount}
            </Text>
          </View>
        </View>
      </View>
    );
  };

  const renderConditionItem = (title, isOk, index) => {
    if (isOk) {
      return (
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
          <Text style={{color: '#333', fontSize: 13, flex: 1}}>{title}</Text>
          <Image
            source={Images.checked}
            resizeMode={'contain'}
            style={{width: screen.PIXEL_40, height: screen.PIXEL_40}}
          />
        </View>
      );
    } else {
      return (
        <TouchableWithoutFeedback
          onPress={() => {
            if (index === 0 || index === 1) {
              DeviceEventEmitter.emit(AppEvent.update_vip);
              navigation.navigate('Vip');
            } else if (index === 2) {
              navigation.navigate('Account');
            }
          }}>
          <View
            style={{
              width: '100%',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}>
            <Text style={{color: '#FF0F00', fontSize: 13, flex: 1}}>
              {title}
            </Text>
            <View
              style={{
                width: screen.PIXEL_40,
                height: screen.PIXEL_40,
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <Image
                source={Images.clear}
                resizeMode={'contain'}
                style={{width: screen.PIXEL_20, height: screen.PIXEL_20}}
              />
            </View>
          </View>
        </TouchableWithoutFeedback>
      );
    }
  };
  const renderRuleItem = (top = 0, str) => {
    return (
      <View style={{width: '100%', flexDirection: 'row', marginTop: top}}>
        {/*<Text style={{fontFamily:getffly("regular"), color: '#000', fontSize: 13,height:20,}}>{"·"}</Text>*/}
        <Text
          style={{fontFamily: getffly('regular'), color: '#000', fontSize: 13}}>
          {' ' + str}
        </Text>
      </View>
    );
  };

  function orderItem(item, index) {
    return (
      <View style={{marginTop: 20}} key={index.toString()}>
        <ShadowBoxView
          shadowOption={{
            radius: screen.PIXEL_40,
            color: '#000',
            x: 0,
            y: 0,
            border: 10,
          }}>
          <View
            style={{
              width: '100%',
              height: screen.PIXEL_250,
              flexDirection: 'row',
              backgroundColor: '#FFFFFF',
              borderRadius: screen.PIXEL_50,
              alignItems: 'center',
              paddingHorizontal: screen.PIXEL_30,
            }}>
            <View
              style={{
                overflow: 'hidden',
                width: screen.PIXEL_170,
                height: screen.PIXEL_200,
                borderRadius: screen.PIXEL_16,
                backgroundColor: '#E9F5F6',
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <Image
                source={{uri: item.icon}}
                style={{width: screen.PIXEL_140, height: screen.PIXEL_160}}
              />
            </View>

            <View
              style={{
                flex: 1,
                marginHorizontal: screen.PIXEL_30,
                justifyContent: 'space-between',
              }}>
              <Text
                style={{
                  fontFamily: getffly('bold'),
                  color: '#000',
                  fontSize: 19,
                }}>
                {item.name}
              </Text>
              <Text
                style={{
                  fontFamily: getffly('regular'),
                  color: '#999',
                  fontSize: 12,
                }}>
                {item.time}
              </Text>
              <Text
                style={{
                  fontFamily: getffly('regular'),
                  color: '#999',
                  fontSize: 12,
                }}>
                {Constants.order.order_id + ':' + item.id}
              </Text>

              <Text style={{fontSize: 19, color: '#000', marginTop: 20}}>
                {Constants.appsymbol}
                <Text style={{fontWeight: 'bold'}}> {item.deposit}</Text>
              </Text>
            </View>
          </View>
        </ShadowBoxView>
      </View>
    );
  }

  function renderMyOrders() {
    let myTask = data.my_task;

    if (!myTask.length) return null;
    return (
      <View
        style={{
          width: '100%',
          flexDirection: 'column',
          marginTop: screen.PIXEL_60,
        }}>
        <Text
          style={{
            fontFamily: getffly('regular'),
            color: '#005652',
            fontSize: 14,
            lineHeight: screen.PIXEL_30,
            marginLeft: screen.PIXEL_20,
          }}>
          {Constants.order.my_recent_orders}
        </Text>
        {myTask.map((item, index) => {
          return orderItem(item, index);
        })}
      </View>
    );
  }

  const renderContent = () => {
    const {
      str1,
      str2,
      str3,
      isLevelOk,
      isLimitOk,
      isBalanceOk,
      isContinue,
    } = getConvertData();
    return (
      <View
        style={{
          width: screen.width,
          backgroundColor: '#fff',
          borderTopLeftRadius: screen.PIXEL_80,
          borderTopRightRadius: screen.PIXEL_80,
        }}>
        <View
          style={{
            marginVertical: screen.PIXEL_50,
            marginHorizontal: screen.PIXEL_80,
          }}>
          {renderConditionItem(str1, isLevelOk, 0)}
          <View style={{height: screen.PIXEL_25}} />
          {renderConditionItem(str2, isLimitOk, 1)}
          <View style={{height: screen.PIXEL_25}} />
          {renderConditionItem(str3, isBalanceOk, 2)}
        </View>


          <View
            style={{
              width: screen.width,
              backgroundColor: '#fff',
              borderTopLeftRadius: screen.PIXEL_80,
              borderTopRightRadius: screen.PIXEL_80,
                shadowColor:'#999',
                shadowOffset:{width:1,height:1},
                shadowOpacity:0.3,
                shadowRadius:0,
            }}>
            <View
              style={{
                marginVertical: screen.PIXEL_50,
                marginHorizontal: screen.PIXEL_80,
              }}>
              <Text
                style={{
                  fontFamily: getffly('regular'),
                  color: '#000',
                  fontSize: 14,
                }}>
                {Constants.order.rules}
              </Text>
              {renderRuleItem(8, Constants.order.rule_1)}
              {renderRuleItem(6, Constants.order.rule_2)}
              {renderRuleItem(6, Constants.order.rule_3)}

              {renderMyOrders()}
            </View>
          </View>

      </View>
    );
  };
  return (
    <View style={styles.container}>
      <Header title={Constants.order.title} navigation={navigation} />

      {data && (
        <View style={{flex: 1}}>
          <ScrollView
          >
            {renderTop()}
            {renderContent()}
          </ScrollView>
          <View style={{height: 1, backgroundColor: '#fff', width: '100%'}}>
            <View
              style={{
                height: 1,
                backgroundColor: 'rgba(32,32,32,0.3)',
                marginHorizontal: screen.PIXEL_30,
              }}
            />
          </View>
          <View
            style={{
                position:'fixed',
                bottom:0,left:0,right:0,
              flexDirection: 'row',
              alignItems: 'flex-end',
              justifyContent: 'space-between',
              padding: screen.PIXEL_30,
              backgroundColor: '#fff',
            }}>
            <Text style={{color: '#000', fontSize: 19}}>
              {Constants.appsymbol}
              <Text style={{fontSize: 28, fontWeight: 'bold'}}>
                {' '}
                {data.type_data.amountRange.min}
              </Text>
            </Text>

            {getConvertData().isContinue ? (
              <TouchableOpacity
                style={[styles.continueBtn, {backgroundColor: '#377C74'}]}
                onPress={showGrabbing}>
                <Text style={{color: '#fff', fontSize: 12}}>{Constants.order.grab_now}</Text>
              </TouchableOpacity>
            ) : (
              <View style={[styles.continueBtn, {backgroundColor: '#666'}]}>
                <Text style={{color: '#fff', fontSize: 12}}>{Constants.order.grab_now}</Text>
              </View>
            )}
          </View>
        </View>
      )}

      <Grabbing ref={grabDialog} />
      <OrderConfirm ref={confirmDialog} order={order} navigation={navigation} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E2FDFF',
  },
  orderImage: {
    width: screen.PIXEL_300,
    height: screen.PIXEL_350,
  },
  tagBg: {
    height: screen.PIXEL_80,
    minWidth: screen.PIXEL_270,
    paddingHorizontal: 10,
    backgroundColor: 'rgba(55,124,116,0.26)',
    borderTopLeftRadius: screen.PIXEL_40,
    borderBottomLeftRadius: screen.PIXEL_40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  continueBtn: {
    height: screen.PIXEL_90,
    width: screen.PIXEL_320,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: screen.PIXEL_20,
    borderBottomRightRadius: screen.PIXEL_40,
  },
});
